<template>
  <a-card class="approval-history-card" title="审批历史">
    <template #extra>
      <a-space>
        <a-button size="small" @click="refreshData">
          <template #icon>
            <icon-refresh />
          </template>
          刷新
        </a-button>
        <a-button size="small" type="primary" @click="exportHistory">
          <template #icon>
            <icon-download />
          </template>
          导出记录
        </a-button>
      </a-space>
    </template>

    <!-- 审批统计 -->
    <div class="approval-summary">
      <a-row :gutter="16" class="mb-4">
        <a-col :span="6">
          <a-statistic title="审批节点" :value="summary.totalNodes" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="已完成" :value="summary.completedNodes" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="进行中" :value="summary.processingNodes" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="总耗时" :value="summary.totalDays" suffix="天" />
        </a-col>
      </a-row>
    </div>

    <!-- 审批流程图 -->
    <div class="approval-flow">
      <div class="flow-title">审批流程</div>
      <div class="flow-container">
        <div v-if="props.loading" class="loading-container">
          <a-spin size="large" />
        </div>
        
        <div v-else class="flow-timeline">
          <div v-for="(record, index) in approvalHistory" :key="record.id" class="timeline-item">
            <div class="timeline-dot" :class="getTimelineDotClass(record.status)">
              <icon-check v-if="record.status === 'approved'" class="dot-icon" />
              <icon-close v-else-if="record.status === 'rejected'" class="dot-icon" />
              <icon-clock-circle v-else-if="record.status === 'processing'" class="dot-icon" />
              <icon-minus v-else class="dot-icon" />
            </div>
            
            <div class="timeline-content">
              <div class="approval-card" :class="getApprovalCardClass(record.status)">
                <div class="approval-header">
                  <div class="approval-title">
                    <span class="node-name">{{ record.nodeName }}</span>
                    <a-tag :color="getStatusColor(record.status)" size="small">
                      {{ getStatusText(record.status) }}
                    </a-tag>
                  </div>
                  <div class="approval-time">
                    <span v-if="record.startTime">开始：{{ record.startTime }}</span>
                    <span v-if="record.endTime">完成：{{ record.endTime }}</span>
                    <span v-if="record.duration" class="duration">耗时：{{ record.duration }}天</span>
                  </div>
                </div>
                
                <div class="approval-body">
                  <div class="approver-info">
                    <a-avatar :size="32" class="approver-avatar">
                      <img v-if="record.approverAvatar" :src="record.approverAvatar" alt="头像" />
                      <span v-else>{{ record.approverName?.charAt(0) || '?' }}</span>
                    </a-avatar>
                    <div class="approver-details">
                      <div class="approver-name">{{ record.approverName || '待分配' }}</div>
                      <div class="approver-role">{{ record.approverRole || '审批人' }}</div>
                    </div>
                  </div>
                  
                  <div v-if="record.comment" class="approval-comment">
                    <div class="comment-label">审批意见：</div>
                    <div class="comment-content">{{ record.comment }}</div>
                  </div>
                  
                  <div v-if="record.attachments && record.attachments.length > 0" class="approval-attachments">
                    <div class="attachments-label">相关附件：</div>
                    <div class="attachments-list">
                      <a-tag 
                        v-for="attachment in record.attachments" 
                        :key="attachment.id"
                        class="attachment-tag"
                        @click="downloadAttachment(attachment)"
                      >
                        <template #icon>
                          <icon-file />
                        </template>
                        {{ attachment.name }}
                      </a-tag>
                    </div>
                  </div>
                  
                  <div v-if="record.nextNodes && record.nextNodes.length > 0" class="next-nodes">
                    <div class="next-nodes-label">下一步：</div>
                    <div class="next-nodes-list">
                      <a-tag 
                        v-for="nextNode in record.nextNodes" 
                        :key="nextNode.id"
                        color="blue"
                        size="small"
                      >
                        {{ nextNode.name }}
                      </a-tag>
                    </div>
                  </div>
                </div>
                
                <div v-if="record.status === 'processing' && record.actions" class="approval-actions">
                  <a-space>
                    <a-button 
                      v-for="action in record.actions" 
                      :key="action.key"
                      :type="action.type"
                      :status="action.status"
                      size="small"
                      @click="handleAction(record, action)"
                    >
                      {{ action.label }}
                    </a-button>
                  </a-space>
                </div>
              </div>
            </div>
            
            <div v-if="index < approvalHistory.length - 1" class="timeline-line"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 审批操作弹窗 -->
    <a-modal
      v-model:visible="actionModalVisible"
      :title="actionModalTitle"
      width="600px"
      @ok="handleActionSubmit"
      @cancel="resetActionForm"
    >
      <a-form
        ref="actionFormRef"
        :model="actionForm"
        :rules="actionRules"
        layout="vertical"
      >
        <a-form-item field="action" label="审批操作" required>
          <a-radio-group v-model="actionForm.action">
            <a-radio value="approve">通过</a-radio>
            <a-radio value="reject">拒绝</a-radio>
            <a-radio value="return">退回</a-radio>
            <a-radio value="transfer">转办</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item 
          v-if="actionForm.action === 'transfer'"
          field="transferTo" 
          label="转办给" 
          required
        >
          <a-select v-model="actionForm.transferTo" placeholder="请选择转办人">
            <a-option value="user1">张三 - 部门经理</a-option>
            <a-option value="user2">李四 - 副总经理</a-option>
            <a-option value="user3">王五 - 总经理</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item 
          v-if="actionForm.action === 'return'"
          field="returnTo" 
          label="退回到" 
          required
        >
          <a-select v-model="actionForm.returnTo" placeholder="请选择退回节点">
            <a-option value="node1">申请提交</a-option>
            <a-option value="node2">初审</a-option>
            <a-option value="node3">复审</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item field="comment" label="审批意见" required>
          <a-textarea
            v-model="actionForm.comment"
            :auto-size="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入审批意见"
          />
        </a-form-item>
        
        <a-form-item field="attachments" label="附件">
          <a-upload
            ref="actionUploadRef"
            :file-list="actionFileList"
            :limit="3"
            multiple
            accept=".pdf,.doc,.docx,.jpg,.png"
            @change="handleActionFileChange"
            @remove="handleActionFileRemove"
          >
            <template #upload-button>
              <div class="upload-area-small">
                <icon-plus class="upload-icon-small" />
                <div class="upload-text-small">上传相关附件</div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import {
  IconRefresh,
  IconDownload,
  IconCheck,
  IconClose,
  IconClockCircle,
  IconMinus,
  IconFile,
  IconPlus
} from '@arco-design/web-vue/es/icon';

// 定义props
const props = defineProps({
  tradeApplicationId: {
    type: String,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
});

// 响应式数据
// const loading = ref(false); // 使用父组件传递的loading状态
const actionModalVisible = ref(false);
const actionModalTitle = ref('审批操作');
const actionFormRef = ref(null);
const actionUploadRef = ref(null);
const approvalHistory = ref([]);
const currentRecord = ref(null);
const currentAction = ref(null);
const actionFileList = ref([]);

// 审批统计
const summary = computed(() => {
  const totalNodes = approvalHistory.value.length;
  const completedNodes = approvalHistory.value.filter(item => 
    ['approved', 'rejected'].includes(item.status)
  ).length;
  const processingNodes = approvalHistory.value.filter(item => 
    item.status === 'processing'
  ).length;
  const totalDays = approvalHistory.value.reduce((sum, item) => 
    sum + (item.duration || 0), 0
  );
  
  return {
    totalNodes,
    completedNodes,
    processingNodes,
    totalDays
  };
});

// 审批操作表单数据
const actionForm = reactive({
  action: '',
  transferTo: '',
  returnTo: '',
  comment: '',
  attachments: []
});

// 审批操作表单验证规则
const actionRules = {
  action: [
    { required: true, message: '请选择审批操作' }
  ],
  transferTo: [
    { required: true, message: '请选择转办人' }
  ],
  returnTo: [
    { required: true, message: '请选择退回节点' }
  ],
  comment: [
    { required: true, message: '请输入审批意见' },
    { minLength: 5, message: '审批意见至少5个字符' }
  ]
};

// 获取时间轴点样式
const getTimelineDotClass = (status) => {
  const classMap = {
    'approved': 'dot-approved',
    'rejected': 'dot-rejected',
    'processing': 'dot-processing',
    'pending': 'dot-pending'
  };
  return classMap[status] || 'dot-pending';
};

// 获取审批卡片样式
const getApprovalCardClass = (status) => {
  const classMap = {
    'approved': 'card-approved',
    'rejected': 'card-rejected',
    'processing': 'card-processing',
    'pending': 'card-pending'
  };
  return classMap[status] || 'card-pending';
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    'approved': 'green',
    'rejected': 'red',
    'processing': 'blue',
    'pending': 'gray'
  };
  return colorMap[status] || 'gray';
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'approved': '已通过',
    'rejected': '已拒绝',
    'processing': '审批中',
    'pending': '待审批'
  };
  return textMap[status] || '未知状态';
};

// 加载数据
const loadData = () => {
  // loading.value = true; // 加载状态由父组件控制
  
  // 模拟API调用
  setTimeout(() => {
    const mockData = [
      {
        id: '1',
        nodeName: '申请提交',
        status: 'approved',
        approverName: '申请人',
        approverRole: '项目申请人',
        approverAvatar: '/avatars/applicant.jpg',
        startTime: '2024-01-15 09:00:00',
        endTime: '2024-01-15 09:30:00',
        duration: 0.5,
        comment: '提交土地交易申请，包含完整的项目资料和相关证明文件。',
        attachments: [
          { id: 'att1', name: '申请表.pdf' },
          { id: 'att2', name: '项目说明.doc' }
        ]
      },
      {
        id: '2',
        nodeName: '资料初审',
        status: 'approved',
        approverName: '张三',
        approverRole: '初审员',
        approverAvatar: '/avatars/zhang.jpg',
        startTime: '2024-01-15 10:00:00',
        endTime: '2024-01-16 14:30:00',
        duration: 1.2,
        comment: '申请资料齐全，符合初审要求。项目用地性质明确，相关证明文件有效。建议进入下一审批环节。',
        attachments: [
          { id: 'att3', name: '初审意见.pdf' }
        ]
      },
      {
        id: '3',
        nodeName: '技术评估',
        status: 'approved',
        approverName: '李四',
        approverRole: '技术专家',
        approverAvatar: '/avatars/li.jpg',
        startTime: '2024-01-16 15:00:00',
        endTime: '2024-01-18 16:00:00',
        duration: 2.1,
        comment: '经技术评估，项目规划合理，土地利用方案可行。环境影响评价报告完整，建议通过技术评估。',
        attachments: [
          { id: 'att4', name: '技术评估报告.pdf' },
          { id: 'att5', name: '现场勘查记录.doc' }
        ]
      },
      {
        id: '4',
        nodeName: '财务审核',
        status: 'processing',
        approverName: '王五',
        approverRole: '财务主管',
        approverAvatar: '/avatars/wang.jpg',
        startTime: '2024-01-18 17:00:00',
        endTime: null,
        duration: null,
        comment: null,
        attachments: [],
        actions: [
          { key: 'approve', label: '通过', type: 'primary', status: 'success' },
          { key: 'reject', label: '拒绝', type: 'primary', status: 'danger' },
          { key: 'return', label: '退回', type: 'outline', status: 'warning' }
        ]
      },
      {
        id: '5',
        nodeName: '最终审批',
        status: 'pending',
        approverName: '待分配',
        approverRole: '审批领导',
        approverAvatar: null,
        startTime: null,
        endTime: null,
        duration: null,
        comment: null,
        attachments: [],
        nextNodes: [
          { id: 'next1', name: '签署合同' },
          { id: 'next2', name: '资金划拨' }
        ]
      }
    ];
    
    approvalHistory.value = mockData;
    // loading.value = false; // 加载状态由父组件控制
  }, 800);
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 导出历史记录
const exportHistory = () => {
  // loading.value = true; // 加载状态由父组件控制
  
  // 模拟导出操作
  setTimeout(() => {
    Message.success('审批历史导出成功');
    // loading.value = false; // 加载状态由父组件控制
  }, 1000);
};

// 下载附件
const downloadAttachment = (attachment) => {
  // loading.value = true; // 加载状态由父组件控制
  
  // 模拟下载操作
  setTimeout(() => {
    Message.success(`下载成功：${attachment.name}`);
    // loading.value = false; // 加载状态由父组件控制
  }, 800);
};

// 处理审批操作
const handleAction = (record, action) => {
  currentRecord.value = record;
  currentAction.value = action;
  actionModalTitle.value = `${action.label} - ${record.nodeName}`;
  resetActionForm();
  actionModalVisible.value = true;
};

// 审批文件变化处理
const handleActionFileChange = (fileList, fileItem) => {
  actionForm.attachments = fileList.filter(file => file.status !== 'error');
};

// 审批文件移除处理
const handleActionFileRemove = (fileItem) => {
  return true;
};

// 提交审批操作
const handleActionSubmit = () => {
  actionFormRef.value.validate((errors) => {
    if (errors) {
      return;
    }
    
    // loading.value = true; // 加载状态由父组件控制
    
    // 模拟API调用
    setTimeout(() => {
      Message.success('审批操作成功');
      actionModalVisible.value = false;
      resetActionForm();
      loadData();
    }, 1000);
  });
};

// 重置审批操作表单
const resetActionForm = () => {
  if (actionFormRef.value) {
    actionFormRef.value.resetFields();
  }
  Object.assign(actionForm, {
    action: '',
    transferTo: '',
    returnTo: '',
    comment: '',
    attachments: []
  });
  actionFileList.value = [];
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.approval-history-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.approval-summary {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.approval-flow {
  margin-top: 20px;
}

.flow-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
}

.flow-container {
  position: relative;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.flow-timeline {
  position: relative;
}

.timeline-item {
  position: relative;
  display: flex;
  align-items: flex-start;
  margin-bottom: 24px;
}

.timeline-dot {
  position: relative;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-right: 16px;
  margin-top: 8px;
  z-index: 2;
}

.dot-approved {
  background: #52c41a;
  border: 3px solid #f6ffed;
}

.dot-rejected {
  background: #ff4d4f;
  border: 3px solid #fff2f0;
}

.dot-processing {
  background: #1890ff;
  border: 3px solid #e6f7ff;
  animation: pulse 2s infinite;
}

.dot-pending {
  background: #d9d9d9;
  border: 3px solid #f5f5f5;
}

.dot-icon {
  color: white;
  font-size: 14px;
}

.timeline-line {
  position: absolute;
  left: 15px;
  top: 40px;
  bottom: -24px;
  width: 2px;
  background: #e8e8e8;
  z-index: 1;
}

.timeline-content {
  flex: 1;
  min-width: 0;
}

.approval-card {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s;
}

.card-approved {
  border-color: #52c41a;
  background: #f6ffed;
}

.card-rejected {
  border-color: #ff4d4f;
  background: #fff2f0;
}

.card-processing {
  border-color: #1890ff;
  background: #e6f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.card-pending {
  border-color: #d9d9d9;
  background: #fafafa;
}

.approval-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.approval-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.approval-time {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  font-size: 12px;
  color: #666;
  gap: 2px;
}

.duration {
  color: #1890ff;
  font-weight: 500;
}

.approval-body {
  margin-bottom: 12px;
}

.approver-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.approver-avatar {
  flex-shrink: 0;
}

.approver-details {
  flex: 1;
}

.approver-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.approver-role {
  font-size: 12px;
  color: #666;
}

.approval-comment {
  margin-bottom: 12px;
}

.comment-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.comment-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  background: rgba(0, 0, 0, 0.02);
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #1890ff;
}

.approval-attachments {
  margin-bottom: 12px;
}

.attachments-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
}

.attachments-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.attachment-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.attachment-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.next-nodes {
  margin-bottom: 12px;
}

.next-nodes-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
}

.next-nodes-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.approval-actions {
  border-top: 1px solid #e8e8e8;
  padding-top: 12px;
}

.upload-area-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area-small:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.upload-icon-small {
  font-size: 16px;
  color: #999;
  margin-bottom: 4px;
}

.upload-text-small {
  font-size: 12px;
  color: #666;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(24, 144, 255, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(24, 144, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(24, 144, 255, 0);
  }
}

@media (max-width: 768px) {
  .approval-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .approval-time {
    align-items: flex-start;
  }
  
  .approver-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .timeline-item {
    margin-bottom: 32px;
  }
  
  .timeline-line {
    bottom: -32px;
  }
}
</style>